<?php

namespace app\data\command;

use app\data\model\DataUserAccount;
use app\data\model\DataUserCommission;
use think\admin\Command;
use think\admin\Exception;
use think\console\Input;
use think\console\Output;
use think\Model;

/**
 * 佣金自动结算
 * Class SettleAccounts
 * @package app\data\command
 */
class SettleAccounts extends Command
{
    //已取消
    protected function configure()
    {
        $this->setName('xdata:SettleAccounts');
        $this->setDescription('佣金自动结算');
    }

    /**
     * 业务指令执行
     * @param Input $input
     * @param Output $output
     * @return void
     * @throws Exception
     */
    protected function execute(Input $input, Output $output)
    {
        $this->_autoSettleAccounts();
    }
    /**
     * 默认7天自动结算
     * @throws Exception
     */
    private function _autoSettleAccounts()
    {
        try {
            $length_time = sysconf('can_jiesuantime');
            if(!isset($length_time)) $length_time = 7;
            //获取未结算佣金记录  更改状态与佣金
            $map = [['status', '=',0],['type', '=', 0]];
            $map[] = ['created_at', '<', date('Y-m-d H:i:s', strtotime('-'.$length_time.' days'))];
            [$count, $total] = [0, ($result = DataUserCommission::mk()->where($map)->select())->count()];

            $opera = [];
            $commissModel = new \app\api\model\DataUserCommission();
            $commissModel->startTrans();
            $result->map(function (Model $item) use ($total, &$count) {
                $this->queue->message($total, ++$count, "开始结算佣金");
                $opera[] = $item->save(['status' => 1, 'update_at' => date('Y-m-d H:i:s')]);
                //更改用户佣金数据
                $opera[] = DataUserAccount::mk()->where(['uuid' => $item['uuid']])->dec('wait_amount', $item['commission_amount'])->save();
                $opera[] = DataUserAccount::mk()->where(['uuid' => $item['uuid']])->inc('avail_amount', $item['commission_amount'])->save();
                sysoplog('结算佣金','系统：正常结算佣金'.$item['uuid']);
                $this->queue->message($total, $count, "完成结算佣金", 1);
            });
            if(\Tools::checkArrayResult($opera)){
                $commissModel->commit();
            }else{
                $commissModel->rollBack();
                sysoplog('结算佣金失败','系统：结算佣金：失败');
                //TODO 发短信警告
            }
        } catch (\Exception $exception) {
            $this->queue->error($exception->getMessage());
        }
    }
}
